package com.knowvoyage.knowvoyageserver.service.Impl;

import com.knowvoyage.knowvoyageserver.mapper.UserMapper;
import com.knowvoyage.knowvoyageserver.pojo.entity.User;
import com.knowvoyage.knowvoyageserver.pojo.vo.Result;
import com.knowvoyage.knowvoyageserver.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public Result<Boolean> insert(User user) {
        Long userId = user.getUserId();
        if(userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if(userMapper.selectById(userId) != null) {
            return Result.error(400, "用户ID已存在");
        }
        userMapper.insert(user);
        return Result.success(true);
    }

    @Override
    public Result<User> selectById(Long userId) {
        return Result.success(userMapper.selectById(userId));
    }

    @Override
    public Result<User> selectByPhone(String phone) {
        return Result.success(userMapper.selectByPhone(phone));
    }

    @Override
    public Result<Boolean> update(User user) {
        Long userId = user.getUserId();
        if(userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if(userMapper.selectById(userId) == null) {
            return Result.error(400, "用户ID不存在");
        }
        userMapper.update(user);
        return Result.success(true);
    }

    @Override
    public Result<Boolean> delete(Long userId) {
        if(userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if(userMapper.selectById(userId) == null) {
            return Result.error(400, "用户ID不存在");
        }
        userMapper.delete(userId);
        return Result.success(true);
    }

    @Override
    public Result<List<User>> selectAll() {
        return Result.success(userMapper.selectAll());
    }

    @Override
    public Result<Boolean> updatePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if(user == null) {
            return Result.error(400, "用户ID不存在");
        }
        if(!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.error(400, "旧密码错误");
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        userMapper.update(user);
        return Result.success(true);
    }
}
